import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import {
  Button,
  Card,
  Form,
  Input,
  Modal,
  Space,
  Table,
  message,
  Popconfirm,
  DatePicker,
  ConfigProvider,
} from 'antd';
import React, { useEffect, useState } from 'react';
import { getQuoteList, addQuote, updateQuote, deleteQuoteBatch, Quote } from '@/services/QuoteService';
import styles from './index.less';
import dayjs from 'dayjs';
import zhCN from 'antd/locale/zh_CN';
import { famousPersonId } from '@/services';

const QuoteAdmin: React.FC = () => {
  const [quotes, setQuotes] = useState<Quote[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingQuote, setEditingQuote] = useState<Quote | null>(null);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [searchForm] = Form.useForm();

  // 获取语录列表
  const fetchQuotes = async (page = pagination.current, pageSize = pagination.pageSize) => {
    try {
      const values = await searchForm.validateFields();
      const data = await getQuoteList({
        pageCurrent: page,
        pageSize: pageSize,
        famousPersonId: famousPersonId,
        ...values,
        quoteDate: values.quoteDate ? dayjs(values.quoteDate).format('YYYY-MM-DD') : undefined,
      });
      setQuotes(data.list);
      setPagination({
        current: page,
        pageSize: pageSize,
        total: data.totalCount,
      });
    } catch (error) {
      message.error('获取语录列表失败');
    }
  };

  useEffect(() => {
    fetchQuotes();
  }, []);

  // 处理表单提交
  const handleSubmit = async (values: any) => {
    try {
      const submitData = {
        ...editingQuote,  // 保留原有数据
        ...values,  // 覆盖表单提交的数据
        quoteDate: values.quoteDate ? dayjs(values.quoteDate).format('YYYY-MM-DD') : undefined,
      };

      if (editingQuote) {
        await updateQuote(submitData);
        message.success('更新成功');
      } else {
        await addQuote({ ...submitData, famousPersonId: famousPersonId });
        message.success('添加成功');
      }
      setModalVisible(false);
      form.resetFields();
      fetchQuotes();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理删除
  const handleDelete = async (id: number) => {
    try {
      await deleteQuoteBatch([id]);  // 使用正确的函数名
      message.success('删除成功');
      fetchQuotes();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 处理搜索
  const handleSearch = () => {
    setPagination(prev => ({ ...prev, current: 1 }));  // 重置到第一页
    fetchQuotes(1, 20);
  };

  // 重置搜索
  const handleReset = () => {
    searchForm.resetFields();
    setPagination(prev => ({ ...prev, current: 1 }));
    fetchQuotes(1, 20);
  };

  const columns = [
    {
      title: '语录内容',
      dataIndex: 'quote',
      key: 'quote',
      width: '40%',
      // 最多显示一行，用省略号
      ellipsis: true,
    },
    {
      title: '来源',
      dataIndex: 'source',
      key: 'source',
      width: '25%',
    },
    {
      title: '时间',
      dataIndex: 'quoteDate',
      key: 'quoteDate',
      width: '15%',
      render: (text: string) => text || '未知时间',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Quote) => (
        <Space>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => {
              setEditingQuote(record);
              form.setFieldsValue({
                ...record,
                quoteDate: record.quoteDate ? dayjs(record.quoteDate) : undefined,
              });
              setModalVisible(true);
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={() => handleDelete(record.id)}
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleTableChange = (newPagination: any) => {
    setPagination(prev => ({
      ...prev,
      current: newPagination.current,
      pageSize: newPagination.pageSize,
    }));
    fetchQuotes(newPagination.current, newPagination.pageSize);
  };

  return (
    <ConfigProvider locale={zhCN}>
      <div className={styles.container}>
        <Card
          title="经典语录管理"
        >
          {/* 添加搜索表单 */}
          <Form
            form={searchForm}
            layout="inline"
            className={styles.searchForm}
            onFinish={handleSearch}
          >
            <Form.Item name="quote" label="语录内容">
              <Input placeholder="请输入语录内容" allowClear />
            </Form.Item>
            <Form.Item name="source" label="来源">
              <Input placeholder="请输入来源" allowClear />
            </Form.Item>
            <Form.Item name="quoteDate" label="时间">
              <DatePicker placeholder="请选择时间" format="YYYY-MM-DD" />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit">
                  搜索
                </Button>
                <Button onClick={handleReset}>重置</Button>
              </Space>
            </Form.Item>
            <Form.Item>
              <Space style={{ marginLeft: 20 }}>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => {
                    setEditingQuote(null);
                    form.resetFields();
                    setModalVisible(true);
                  }}
                >
                  添加语录
                </Button>
              </Space>
            </Form.Item>
          </Form>

          <Table
            columns={columns}
            dataSource={quotes}
            scroll={{ y: 'calc(100vh - 380px)', scrollToFirstRowOnChange: false }}
            className={styles.table}
            rowKey="id"
            pagination={{
              ...pagination,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条`,
              pageSizeOptions: [ '20', '50', '100'],
            }}
            onChange={handleTableChange}
          />
        </Card>

        <Modal
          title={editingQuote ? '编辑语录' : '添加语录'}
          open={modalVisible}
          onCancel={() => setModalVisible(false)}
          onOk={() => form.submit()}
          destroyOnClose
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
          >
            <Form.Item
              name="quote"
              label="语录内容"
              rules={[{ required: true, message: '请输入语录内容' }]}
            >
              <Input.TextArea rows={4} />
            </Form.Item>
            <Form.Item
              name="source"
              label="来源"
              rules={[{ required: true, message: '请输入语录来源' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="quoteDate"
              label="语录时间"
            >
              <DatePicker style={{ width: '100%' }} placeholder="请选择时间（可选）" format="YYYY-MM-DD" />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </ConfigProvider>
  );
};

export default QuoteAdmin; 